package com.hwd.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.hwd.srb.common.constant.Constants;
import com.hwd.srb.common.util.JwtUtils;
import com.hwd.srb.common.exception.Assert;
import com.hwd.srb.common.result.R;
import com.hwd.srb.common.result.ResponseEnum;
import com.hwd.srb.core.hfb.RequestHelper;
import com.hwd.srb.core.pojo.vo.UserBindVO;
import com.hwd.srb.core.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author 黄伟东/Victor
 * @since 2022-03-10
 */
@RestController
@RequestMapping("/api/core/userBind")
@Api(tags = "账户绑定接口")
@Slf4j
public class ApiUserBindController {

    @Resource
    private UserBindService userInfoService;

    /**
     * 会员账号绑定，返回汇付宝表单字符串
     *
     * @param userBindVO 账户绑定对象
     * @return com.hwd.srb.common.result.R
     */
    @ApiOperation("账户绑定提交数据")
    @PostMapping("/auth/bind")
    public R bind(@ApiParam(value = "账户绑定对象", required = true) @RequestBody UserBindVO userBindVO,
                  HttpServletRequest request) {

//        // 获取token鉴权 TODO gateway网关添加统一鉴权过滤器
//        String token = request.getHeader(Constants.TOKEN);
//        Assert.notNull(token, ResponseEnum.LOGIN_AUTH_ERROR);

//        boolean bToken = JwtUtils.checkToken(token);
//        Assert.isTrue(bToken, ResponseEnum.WEIXIN_FETCH_USERINFO_ERROR);

//        Long userId = JwtUtils.getUserId(token);
        Long userId = Long.valueOf(request.getHeader(Constants.USER_ID));

        // 调用业务层，通过hfbApi接口生成汇付宝表单
        String formStr = userInfoService.bind(userBindVO, userId);

        return R.ok().data("formStr", formStr);
    }

    /**
     * 账户绑定异步回调
     *
     * @param request 请求对象， 包含结果参数
     * @return com.hwd.srb.common.result.R
     */
    @ApiOperation("账户绑定异步回调")
    @PostMapping("/notify")
    public String notifyBind(HttpServletRequest request) {
        // 解析汇付宝回调参数
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("用户账号绑定异步回调：" + JSON.toJSONString(paramMap));

        //会员id
        String userId = (String)paramMap.get("agentUserId");

        // 校验签名，防止欺骗通知，商户收到通知后，要求验签成功后处
        boolean signEquals = RequestHelper.isSignEquals(paramMap);
        if (!signEquals) {
            log.error("用户账号绑定异步回调名签错误：" + JSON.toJSONString(paramMap));
            return "fail";
        }

        // 幂等性检查 回调异步通知接口幂等性检查(防止同一个写入请求被反复执行)
        boolean hasBind = userInfoService.hasBindById(userId);
        if (!hasBind) {
            // 调用业务层修改绑定状态
            userInfoService.notifyBind(paramMap);
        }

        return "success";
    }
}

